<template>
<div>
  <!-- 操作选项 -->
  <el-row :gutter="20">
    <el-col :span="4">
      <!-- .native 监听组件根元素的原生事件 -->
      <!-- 这里将 loadUsers 作为原生事件的处理函数，一定要手动传1，否则loadUsers的第一个参数就是事件源对象，把事件源对象当作页码 -->
        <el-input
        placeholder="请输入内容"
        v-model="searchText"
        @keyup.enter.native="loadUsers(1)">
        <i slot="prefix" class="el-input__icon el-icon-search"></i>
      </el-input>
    </el-col>
    <el-col :span="4">
      <el-button type="primary" round @click="addFormVisible = true">添加用户</el-button>
    </el-col>
  </el-row>
  <!-- 卡片内容 -->
  <!-- 表格组件 -->
  <!-- 表格列组件：列名+列值 内部自动遍历 -->
  <el-table
    :data="users"
    border
    stripe
    style="width: 100%"
    v-loading="tableLoading">
    <el-table-column
      type="index">
  </el-table-column>
    <el-table-column
      prop="username"
      label="姓名"
      width="180">
    </el-table-column>
    <el-table-column
      prop="email"
      label="邮箱"
      width="180">
    </el-table-column>
    <el-table-column
      prop="mobile"
      label="电话">
    </el-table-column>
    <el-table-column label="用户状态">
      <template slot-scope="scope">
      <el-switch
        v-model="scope.row.mg_state"
        @change="handleChangeState(scope.row)"
        active-color="#13ce66"
        inactive-color="#ff4949">
      </el-switch>
      </template>
    </el-table-column>
    <!--
      自定义表格列
      1.自定义内容写到<template slot-scope="scope"></template>
        slot-scope是固定的属性
        值"scope"是随便起的名字
        在template中，scope.row用于获取当前遍历项(item)
        scope.$index就是遍历的索引
      -->
    <el-table-column label="操作">
      <template slot-scope="scope">
        <el-button
          @click="$refs.userEditEl.showEditDialog(scope.row)"
          type="primary"
          icon="el-icon-edit"
          circle></el-button>
        <el-button
          type="danger"
          @click="handleDelete(scope.row)"
          icon="el-icon-delete"
          circle></el-button>
          <el-button
          type="success"
          icon="el-icon-check"
          circle
          @click="$refs.userEditRoleEl.showEditRoleDialog(scope.row)"></el-button>
      </template>
    </el-table-column>
  </el-table>
  <!--
    分页组件
    el-pagination
    background 带有背景色
    layout 分页结构 prev显示上一页 pager 页码 next 下一页
    total 数据总条数
    current-change 页码改变触发该事件
  -->
  <el-pagination
    background
    layout="prev, pager, next"
    :total="total"
    :page-size="5"
    :current-page.sync="page"
    @current-change="loadUsers">
  </el-pagination>
  <!-- 添加对话框组件 -->
  <el-dialog title="添加用户" :visible.sync="addFormVisible" width="500px">
    <el-form :rules="addFormRules" ref="addFormEl" :model="addFormData" size="small">
      <el-form-item prop="username" label="用户名" label-width="80px">
        <el-input v-model="addFormData.username" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item prop="password" label="密码" label-width="80px">
        <el-input v-model="addFormData.password" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item prop="email" label="邮箱" label-width="80px">
        <el-input v-model="addFormData.email" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item prop="mobile" label="电话" label-width="80px">
        <el-input v-model="addFormData.mobile" autocomplete="off"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="addFormVisible = false">取 消</el-button>
      <el-button type="primary" @click.prevent="handleAdd">确 定</el-button>
    </div>
  </el-dialog>
  <!-- 编辑用户对话框 -->
  <!--
    1.为组件添加一个ref属性，起个名字
    2.然后可以在当前组件中通过this.$refs.组件的ref名字来访问到这个组件
    this.$refs.userEditEl 可以直接访问到UserEdit组件
   -->
  <UserEdit ref="userEditEl" v-on:edit-success="loadUsers"></UserEdit>
  <UserEditRole ref="userEditRoleEl"></UserEditRole>
</div>
</template>
<script>
// import { getUserList, addUser } from '@/api/user'
import * as User from '@/api/user'
import UserEdit from './edit'
import UserEditRole from './edit-role'
export default {
  name: 'UserList',
  data () {
    return {
      users: [],
      searchText: '',
      addFormVisible: false, // 对话框是否显示
      addFormData: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      tableLoading: true,
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' }
        ]
      },
      total: 0,
      page: 1
    }
  },
  async created () {
    // 除了登录接口，其他接口都需要身份令牌才能访问
    this.loadUsers()
  },
  methods: {
    async loadUsers (page = 1) {
      this.tableLoading = true // 开始加载loading效果
      const { data } = await User.getUserList({ pagenum: page, pagesize: 5, query: this.searchText })
      this.users = data.users
      this.total = data.total
      this.tableLoading = false // 取消加载loading效果
    },
    handleAdd () {
      this.$refs.addFormEl.validate(valid => {
        if (!valid) { // 验证失败，什么都不做
          return
        }
        this.submitAdd() // 验证通过，提交表单
      })
    },
    async submitAdd () {
      const { meta } = await User.addUser(this.addFormData)
      if (meta.status === 201) {
        this.$refs.addFormEl.resetFields() // 清空表单数据
        this.addFormVisible = false
        this.loadUsers() // 重新加载数据列表
      }
    },
    handleDelete (item) {
      this.$confirm('确认删除吗？', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => { // 确认
        const { meta } = await User.deleteById(item.id)
        if (meta.status === 200) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.loadUsers(this.page)
        }
      }).catch(() => { // 取消
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    async handleChangeState (item) {
      const { meta, data } = await User.changeState(item.id, item.mg_state)
      if (meta.status === 200) {
        this.$message({
          type: 'success',
          message: `${data.mg_state ? '启用' : '禁用'}用户状态成功`
        })
      }
    }
  },
  components: {
    UserEdit,
    UserEditRole
  }
}
</script>
<style scoped>
.el-table {
  margin-top: 20px;
}
.el-pagination {
  margin-top: 15px;
}
</style>
